﻿using Autofac.Extras.DynamicProxy;
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using Truron.Purchase.Interface;
using Truron.Purchase.Model;
using Truron.Purchase.Model.RemoteModel;
using Truron.Purchase.Service.DbContext;
using Truron.Purchase.Utility;
using Truron.Purchase.Utility.RedisHelper;

namespace Truron.Purchase.Service
{
    [Intercept(typeof(CustomAutofacAop))]
    public class Purchase_FileInfoService: IPurchase_FileInfoService
    {
        private List<Purchase_FileInfo> Init(bool isInit = false)
        {
            try
            {
                if (isInit)//初始化
                    RedisBase.Hash_Remove(StaticConstraint.PurchaseFileInfoCacheKey);
                var List = RedisBase.Hash_GetAll<Purchase_FileInfo>(StaticConstraint.PurchaseFileInfoCacheKey);
                if (List != null && List.Count > 0)
                    return List;
                string sql = string.Format(@" select * from Purchase_FileInfo
                                                            where Status!={0} ", (int)Status.delete);
                List = DapperDbContext.Query<Purchase_FileInfo>(sql).ToList();
                if (List.Count > 0)
                {
                    foreach (var item in List)
                        RedisBase.Hash_Set(StaticConstraint.PurchaseFileInfoCacheKey, item.Id, item);
                    RedisBase.Item_SetExpire(StaticConstraint.PurchaseFileInfoCacheKey, DateTime.Now.AddDays(7));
                }
                return List;
            }
            catch (Exception ex)
            {
                LogHelper.Error($"初始化单据数据失败,isInit:{isInit},详细:{ex.ToString()}");
            }
            return new List<Purchase_FileInfo>();
        }
        public List<Purchase_FileInfo> GetFileList(string GrpCode)
        {
            return Init().Where(x => x.GrpCode == GrpCode).ToList();
        }
        public void SaveFile(Purchase_FileInfo entity,UserCache userCache)
        {
            IDbModelService<Purchase_FileInfo> db = new DbModelService<Purchase_FileInfo>();
            IDbTransaction transaction = null;
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    transaction = conn.BeginTransaction();
                    if (entity.Id == 0)
                    {
                        entity.Create(userCache);
                        var Id = db.InsertOne(entity, conn, transaction);
                        RedisBase.Hash_Set(StaticConstraint.PurchaseFileInfoCacheKey, Id, entity);
                        transaction.Commit();
                    }
                    else
                    {
                        entity.Modify(userCache);
                        db.UpdateById(entity, conn, transaction);
                        transaction.Commit();
                        if (entity != null)//更新线索缓存
                        {

                            RedisBase.Hash_Remove(StaticConstraint.PurchaseFileInfoCacheKey, entity.Id.ToString());
                            RedisBase.Hash_Set(StaticConstraint.PurchaseFileInfoCacheKey, entity.Id, entity);
                        }
                    }

                }
            }
            catch (Exception ex)
            {

                transaction.Rollback();
            }
        }

        public void DeleteFile(int fileId, UserCache userCache)
        {
            try
            {
                using (var conn = DapperHelper.Instance.OpenCurrentDbConnection())
                {
                    string sql = "UPDATE [dbo].[Purchase_FileInfo] set [Status] = @Status,[LastUpdateUser] = @LastUpdateUser,[LastUpdateTime] = @LastUpdateTime where Id = @Id";
                    int delcount = conn.Execute(sql, new { Status = Status.delete, LastUpdateUser = userCache.UserId, LastUpdateTime = DateTime.Now, Id = fileId });
                    if (delcount > 0)
                    {
                        RedisBase.Hash_Remove(StaticConstraint.PurchaseFileInfoCacheKey, fileId.ToString());
                    }
                }

            }
            catch (Exception ex)
            {
            }
        }
        public (byte[] file, string type,string filename) DownFile(int fileId)
        {
            Purchase_FileInfo entity = Init().Find(x => x.Id == fileId);
            byte[] filebytes= File.ReadAllBytes(entity.FilePath);
            string contentType = "";
            switch (entity.FileSuffix.ToLower())
            {
                case "jpg":
                case "jpeg":
                case "gif":
                case "png":
                case "webp":
                    contentType = "image/" + entity.FileSuffix.ToLower();
                    break;
                case "bmp":
                    contentType = "application/x-bmp";
                    break;
                case "pdf":
                    contentType = "application/" + entity.FileSuffix.ToLower();
                    break;
                case "txt":
                    contentType = "text/plain";
                    break;
                case "csv":
                    contentType = "";
                    break;
                case "html":
                    contentType = "text/html";
                    break;
                default:
                    contentType = "application/octet-stream";
                    break;
            }

            return (filebytes, contentType,entity.SourceName);
        }
        public Purchase_FileInfo GetFileEntity(int FileId)
        {
            return Init().Find(x => x.Id == FileId);
        }
    }
}
